package com.chenyue.cm.moudules.system.controller;

import com.alibaba.fastjson.JSON;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.C;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.moudules.system.service.SysUserRolesService;
import com.chenyue.cm.moudules.system.service.SysUsersService;
import com.chenyue.cm.moudules.system.utils.PasswordHelper;
import com.chenyue.cm.system.domain.SysUsers;
import com.chenyue.cm.system.domain.SysUsersExample;
import com.chenyue.cm.system.domain.SysUsersRole;
import com.chenyue.cm.system.domain.SysUsersRoleExample;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 用户管理
 *
 * @author chenyue
 * @Description: TODO
 * @file:
 * @throws
 * @date 2018/11/14 15:31
 */
@Controller
@RequestMapping("/sysUsers")
@Api(value = "系统管理-用户", tags = "系统管理-用户")
@ApiSort(4)
public class SysUsersController {

    private final SysUsersService sysUsersService;

    private final SysUserRolesService userRoleService;

    private String themePrefix = C.THEME_Prefix;
    private String page_url_list = themePrefix + "system/sysusers/sysUsersList";
    private String page_url_form = themePrefix + "system/sysusers/sysUsersForm";

    public SysUsersController(SysUsersService sysUsersService, SysUserRolesService userRoleService) {
        this.sysUsersService = sysUsersService;
        this.userRoleService = userRoleService;
    }


    @RequestMapping("/toList")
    public String toList(HttpServletRequest request, HttpServletResponse response, Model model) {

        return page_url_list;
    }


    @RequestMapping("/toForm")
    public String toForm(Model model, HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        SysUsers vo = (id != null && id != "") ? sysUsersService.selectByPrimaryKey(id) : new SysUsers();
        model.addAttribute("vo", vo);
        //获取用户角色信息
        if (id != null) {
            SysUsersRoleExample aExample = new SysUsersRoleExample();
            aExample.createCriteria().andUserIdEqualTo(vo.getId());
            List<SysUsersRole> rolelist = userRoleService.selectByExample(aExample);
            if (rolelist.size() > 0) {
                model.addAttribute("roleid", rolelist.get(0).getRoleId());
            }
        }

        return page_url_form;
    }


    @PostMapping("/getList")
    @ResponseBody
    @ApiOperation(value = "【S4001】获取用户信息列表（分页）", notes = "获取用户信息列表")
    @ApiOperationSupport(order = 1)
    @Log(value = "查询用户列表", type = "1")
    public PageVo<SysUsers> getList(HttpServletRequest request, HttpServletResponse response) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        System.out.println("pageInfo信息===" + JSON.toJSON(pageInfo));
        PageVo<SysUsers> result = sysUsersService.getPageBean(pageInfo, SysUsers.class);
        return result;
    }

    /**
     * 【API】----【获取列表数据----带分页】
     *
     * @param request
     * @param response
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/getListPC")
    @ResponseBody
    @ApiOperation(value = "【S4002】获取用户信息列表（分页）", notes = "获取用户信息列表")
    @ApiOperationSupport(order = 2)
    @Log(value = "查询用户列表", type = "1")
    public Success getListPC(HttpServletRequest request, HttpServletResponse response) throws InterruptedException {
        Pageable pageInfo = RequestUtil.getPageable(request);
        System.out.println("pageInfo信息===" + JSON.toJSON(pageInfo));
        PageVo<SysUsers> result = sysUsersService.getPageBean(pageInfo, SysUsers.class);
        return Success.success(result);
    }

    /**
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/getVo")
    @ResponseBody
    @ApiOperation(value = "【S4003】根据id获取单个用户详情", notes = "获取单个用户详情")
    @ApiOperationSupport(order = 3)
    @Log(value = "查询单个用户信息", type = "1")
    public Success getVo(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        SysUsers userVo = new SysUsers();
        if (id != null && !"".equals(id)) {
            userVo = sysUsersService.selectByPrimaryKey(id);
        }
        return Success.success(userVo);
    }

    /**
     * 【API】---- 根据用户id获取角色ids
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/getRolesIdByUid")
    @ResponseBody
    @ApiOperation(value = "【S4004】根据用户id获取角色ids", notes = "根据用户id获取角色ids")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "角色id", name = "id", dataType = "string", required = true),
    })
    public Success getRolesIdByUid(HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("id");
        List<String> roleList = new ArrayList<>();
        // 返回当前用户角色信息
        SysUsersRoleExample aExample = new SysUsersRoleExample();
        aExample.createCriteria().andUserIdEqualTo(userId);
        List<SysUsersRole> userRoleList = userRoleService.selectByExample(aExample);
        for (SysUsersRole sysUsersRole : userRoleList) {
            roleList.add(sysUsersRole.getRoleId());
        }
        return Success.success( roleList.get(0));
    }


    /**
     * 保存用户信息
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    @ApiOperation(value = "【S4005】保存用户信息", notes = "保存用户信息")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户角色id", name = "roles", dataType = "string", required = true),
    })
    @Log(value = "保存用户信息", type = "1")
    public Success save(SysUsers vo, HttpServletRequest request, HttpServletResponse response, Model model) {
        String id = request.getParameter("id");
        String roleid = request.getParameter("roles");

        if (id != null && id != "") {
            vo.setPassword("123456");
            vo.setPassword(PasswordHelper.encryptPassword(vo));
            sysUsersService.getBaseMapper().updateById(vo);
        } else {
            vo.setPassword(PasswordHelper.encryptPassword(vo));
            vo.setId(UUID.randomUUID().toString().replace("-", ""));
            sysUsersService.save(vo);
        }

        //保存用户---角色信息
        SysUsersRoleExample aExample = new SysUsersRoleExample();
        aExample.createCriteria().andUserIdEqualTo(vo.getId());
        userRoleService.deleteByExample(aExample);
        SysUsersRole aRole = new SysUsersRole(roleid, vo.getId());
        aRole.setId(UUID.randomUUID().toString().replace("-", ""));
        userRoleService.save(aRole);
        return Success.success();
    }


    /**
     * 【API】---- 【保存用户信息】
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @PostMapping("/savePC")
    @ResponseBody
    @ApiOperation(value = "【S4006】保存用户信息", notes = "保存用户信息")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户角色id", name = "roles", dataType = "string", required = true),
    })
    @Log(value = "保存用户信息", type = "1")
    public Success savePC(SysUsers vo, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String roleid = request.getParameter("roles");

        if (id != null && !"".equals(id) || !"".equals(vo.getId())) {
            //vo.setPassword(PasswordHelper.encryptPassword(vo));
            sysUsersService.getBaseMapper().updateById(vo);
        } else {
            vo.setPassword("admin");
            vo.setPassword(PasswordHelper.encryptPassword(vo));
            vo.setId(UUID.randomUUID().toString().replace("-", ""));
            sysUsersService.save(vo);
        }

        //保存用户角色信息
        if (roleid != null) {
            //删除原来的关联关系
            SysUsersRoleExample aExample = new SysUsersRoleExample();
            aExample.createCriteria().andUserIdEqualTo(vo.getId());
            userRoleService.deleteByExample(aExample);
            //设置新的关联关系
            String[] roles = roleid.split(",");
            for (String string : roles) {
                SysUsersRole aRole = new SysUsersRole(string, vo.getId());
                aRole.setId(UUID.randomUUID().toString().replace("-", ""));
                userRoleService.save(aRole);
            }
        }


        return Success.success();
    }


    /**
     * 用户修改密码
     *
     * @param password
     * @param newPassWord
     * @param passwordAgain
     * @return
     */
    @PostMapping(value = "/resetpwd")
    @ResponseBody
    @ApiOperation(value = "【S3007】更新用户密码", notes = "更新用户密码")
    @ApiOperationSupport(order = 7)
    public Success updatePassWord(@RequestParam String password, @RequestParam String newPassWord,
                            @RequestParam String passwordAgain) {
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassWord) || StringUtils.isEmpty(passwordAgain)) {
            return Success.error("账号或密码错误！");
        }
        if (!newPassWord.equals(passwordAgain)) {
            return Success.error("俩次密码不一致，请重新确认");
        }
        return this.sysUsersService.updatePassWord(password, newPassWord);
    }


    /**
     * 删除用户信息信息
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    @ApiOperation(value = "【S3008】删除单个用户信息", notes = "删除单个用户信息")
    @ApiOperationSupport(order = 8)
    @Log(value = "删除单个用户信息", type = "1")
    public Success delete(@PathVariable String id, HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");

        //删除用户信息
        SysUsersExample aExample = new SysUsersExample();
        aExample.createCriteria().andIdEqualTo(id);
        sysUsersService.deleteByExample(aExample);

        return Success.success();
    }


    /**
     * 【API】---- 【删除用户信息】
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    @ApiOperation(value = "【S3009】批量删除用户信息", notes = "批量删除用户信息")
    @ApiOperationSupport(order = 9)
    @Log(value = "批量删除用户信息", type = "1")
    public Success delete(HttpServletRequest request, HttpServletResponse response, Model model) {

        response.setContentType("text/html;charset=utf-8");
        String ids = request.getParameter("ids");
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            //删除用户信息
            SysUsersExample aExample = new SysUsersExample();
            aExample.createCriteria().andIdEqualTo(idString);
            sysUsersService.deleteByExample(aExample);
        }

        return Success.success();
    }


}
